package com.cddx.logistics.service.impl;

import com.cddx.logistics.domain.dto.QueryDTO;
import com.cddx.logistics.domain.dto.RoleMenuDTO;
import com.cddx.logistics.domain.pojo.Role;
import com.cddx.logistics.domain.pojo.RoleMenu;
import com.cddx.logistics.domain.vo.SelectObject;
import com.cddx.logistics.domain.vo.UserVO;
import com.cddx.logistics.mapper.RoleMapper;
import com.cddx.logistics.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleMapper roleMapper;


    @Override
    public boolean addRole(Role role) {
        return roleMapper.addRole(role) > 0;
    }

    @Override
    public boolean updateRole(Role role) {
        return roleMapper.updateRole(role) > 0;
    }

    @Override
    public boolean deleteRole(Integer id) {
        return roleMapper.deleteRole(id) > 0;
    }

    @Override
    public PageInfo<Role> queryPage(QueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getLimit());
        List<Role> list = roleMapper.queryPage(queryDTO);
        return new PageInfo<>(list);
    }

    @Override
    public List<SelectObject> queryAll() {
        return roleMapper.queryAll();
    }

    @Override
    public boolean deleteIds(Integer[] ids) {
        return roleMapper.deleteIds(ids) > 0;
    }

    @Override
    public List<Integer> queryMenu(Integer id) {
        return roleMapper.queryMenu(id);
    }

    @Override
    @Transactional
    public boolean addMenuAuth(RoleMenuDTO roleMenuDTO) {
        //先删除原有的权限
        roleMapper.deleteMenuByRoleId(roleMenuDTO.getRoleId());
        //检验是否添加了权限
        if(roleMenuDTO.getMenuIds().isEmpty()) return true;
        Integer roleId = roleMenuDTO.getRoleId();
        //批量插入
        return roleMapper.batchInsert(roleMenuDTO.getMenuIds().stream().
                map(menuId -> new RoleMenu(null, roleId, menuId)).
                collect(Collectors.toList()))>0;

    }

}
